# -*- encoding=utf8 -*-

__author__ = "code哥"
import random
import sys
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

dev = False

if dev:
    poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
    from airtest.cli.parser import cli_setup

    if not cli_setup():
        auto_setup(__file__, logdir=None, devices=[
            "Android://127.0.0.1:5037/M960BDPT226TA?cap_method=JAVACAP&&ori_method=ADBORI",
        ])
else:
    import timeout_decorator

    # M960BDPT226TA WIFI 10.0.0.26 48003
    argv1 = str(sys.argv[1])
    argv2 = str(sys.argv[2])
    argv3 = str(sys.argv[3])
    argv4 = str(sys.argv[4])

    if argv2 == 'USB':
        conn_info = 'Android://127.0.0.1:5037/{uuid}?cap_method=JAVACAP&&ori_method=ADBORI'.format(
            uuid=argv1)
        device = connect_device(conn_info)
    else:
        # WIFI模式
        conn_info = 'Android://127.0.0.1:5037/{clientIp}:{port}'.format(
            clientIp=argv3,
            port=argv4)
        print(conn_info)
        device = connect_device(conn_info)

    poco = AndroidUiautomationPoco(device, use_airtest_input=True, screenshot_each_action=False)

    logdir = "{path}/static/source_img/{fileName}/{devices}".format(
        path=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        fileName=str(os.path.abspath(__file__).split('/')[-1]).split('.py')[0],
        devices=argv1)
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    auto_setup(__file__,
               logdir=logdir,
               devices=[conn_info, ],
               project_root="{root}".format(root=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))


def start():
    if not dev:
        set_logdir(logdir)
        # set_current(str(sys.argv[1]))
    # 退到桌面
    home()
    stop_app('com.jifen.qukan')
    sleep(1)
    start_app('com.jifen.qukan')
    home_start()


def home_start():
    sleep(15)
    if poco("com.jifen.qukan:id/a6d").exists():
        poco("com.jifen.qukan:id/a6d").click()
    sleep(0.5)
    acl = poco("com.jifen.qukan:id/acl")
    if acl.exists():
        acl.click()
    ad5 = poco(type="android.widget.ImageView", name="com.jifen.qukan:id/ad5")
    if ad5.exists():
        ad5.click()
    sleep(1)
    nd_list = poco(type="android.widget.LinearLayout", name="com.jifen.qukan:id/nd").children()
    if nd_list.exists():
        for item in nd_list:
            vide = item.offspring("com.jifen.qukan:id/aky", text="小视频")
            if vide.exists():
                item.click()
                break
        while True:
            loop_body()


@timeout_decorator.timeout(60)
def loop_body():
    print('loop_body......')
    sleep(4 + random.randint(0, 5))
    content = poco(type="android.widget.FrameLayout", name="android:id/content")
    bf4 = poco(type="android.widget.ImageView", name="com.jifen.qukan:id/bf4")
    if not bf4.exists():
        content.swipe([0, -0.9])
        return
    if not content.exists():
        ahp = poco(type="android.widget.LinearLayout", name="com.jifen.qukan:id/ahp")
        if ahp.exists():
            ahp.swipe([0, -0.9])
            return
    content.swipe([0, -0.9])


def main():
    try:
        start()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()
